package cmd

import (
	l4g "github.com/alecthomas/log4go"
	"mysqlbackup/cron"
	"os"
	"runtime"
	"time"
)

type FullConfig struct {
	Path string
	HistoryNumber int
	Prefix string
	ClearInc bool
}

type IncrementalConfig struct {
	Path string
	Prefix string
}

func xtrabackupFull()  {
	timestamp := time.Now().Format("20060102.150405")
	l4g.Info("开始执行 全量备份。。。。。 路径 %s",config.FullConfig.Path)
	l4g.Info("执行事件 %s",timestamp)
	fullConfi:=config.FullConfig
	if fullConfi.Prefix == "" {
		fullConfi.Prefix="Full"
	}
	filename :=cron.DealWithFiles(fullConfi.Path,timestamp,fullConfi.Prefix)
	out,err :=xtrabackup(filename)
	if err != nil {
	 l4g.Error("执行备份出现问题 %s 详细 %s",err,out)
		err = os.RemoveAll(filename)
		if err !=nil {
			l4g.Error("清理目录失败  %s  ",filename)
		}
	}else {
		l4g.Info(out)
		cron.RmHistory(fullConfi.Path,fullConfi.HistoryNumber,fullConfi.Prefix)
		if  fullConfi.ClearInc{
			incrementalConfig :=config.IncrementalConfig
			files :=cron.SortFile(incrementalConfig.Path,incrementalConfig.Prefix)
			cron.RmByModTime(incrementalConfig.Path,0,files)
		}
	}
	l4g.Info("the number of goroutines: %v", runtime.NumGoroutine())
}



func xtrabackup(targetDir string,args ...string)(string,error){
	dBconfig:=config.DBconfig
	args = append( []string{
		"--backup",
		"--user="+dBconfig.User,
		"--password="+dBconfig.Password,
		"--target-dir="+targetDir,
	},args...)
	out,err :=ExecuteCommandSimple("xtrabackup",args...)
	return out,err
}


func xtrabackupIncremental(){
	timestamp := time.Now().Format("20060102.150405")
	incrementalConfig :=config.IncrementalConfig
	l4g.Info("开始执行 增量备份。。。。。 路径 %s",incrementalConfig.Path)
	l4g.Info("执行事件 %s",timestamp)
	if incrementalConfig.Prefix == "" {
		incrementalConfig.Prefix = "inc"
	}
	path:=incrementalConfig.Path
	files :=cron.SortFile(path,incrementalConfig.Prefix)
	if len(files) <=0 {
		fullConfi:=config.FullConfig
		if fullConfi.Prefix == "" {
			fullConfi.Prefix="Full"
		}
		path=fullConfi.Path
		files =cron.SortFile(fullConfi.Path,fullConfi.Prefix)
	}
	if len(files) <=0{
		l4g.Warn("没有 基于的 增量 目录 跳过 增量 备份")
		return
	}
	file := files[0]
	filename :=cron.DealWithFiles(incrementalConfig.Path,timestamp,incrementalConfig.Prefix)
	args:=[]string{
		"--incremental-basedir="+path+file.Name(),
	}
	out,err :=xtrabackup(filename,args...)
	if err != nil {
		l4g.Error("执行备份出现问题 %s 详细 %s",err,out)
		err = os.RemoveAll(filename)
		if err !=nil {
			l4g.Error("清理目录失败  %s  ",filename)
		}
	}else {
		l4g.Info(out)
	}
	l4g.Info("the number of goroutines: %v", runtime.NumGoroutine())
}


func init()  {
	c.AddFun("xtrabackupFull",xtrabackupFull)
	c.AddFun("xtrabackupIncremental",xtrabackupIncremental)
}